const BehaviorAll = require("../../../behaviors/behavior_all.js");
const ServiceTicket = require("../../../service/service_ticket.js");
const ServiceSpread = require("../../../service/service_spread.js");
const Url = require("../../../utils/url.js");
const App = getApp();

Component({
  /**
   * behaviors
   */
  behaviors: [BehaviorAll],
  /**
   * 页面的初始数据
   */
  data: {
    onPopupShow: false,
    tickets: [],
    ticket: null,
    ticketImgUrl: null,
    /**
     * 开始页
     */
    startPage: 0
  },

  methods: {
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      const _this = this;
      //
      ServiceTicket.page(0, function (data) {
        _this.setData({
          tickets: data.records
        });
      });
      ServiceSpread.getTicket(res => {
        _this.setData({ ticketImgUrl: res.imgUrl });
      })
      // 领取优惠券
      const id = options.id;
      if (null !== id && undefined !== id) {
        wx.showModal({
          title: '是否领取',
          content: '',
          cancelText: '否',
          confirmText: '是',
          success(res) {
            if (res.cancel) {
            } else if (res.confirm) {
              ServiceTicket.accept(id, function (data) {
                _this.data.tickets.unshift(data);
                _this.setData({
                  tickets: _this.data.tickets
                });
              });
            }
          }
        })
      }

    },

    /**
     * 打开弹出框
     */
    onOpen: function (e) {
      const _this = this;
      const id = e.currentTarget.dataset.id;
      ServiceTicket.findById(id, function (data) {
        _this.setData({
          ticket: data
        });
      });
      _this.setData({ onPopupShow: true })
    },

    /**
     * 关闭弹出框
     */
    onClose: function () {
      const _this = this;
      _this.setData({ onPopupShow: false })
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (options) {
      const _this = this;
      const user = App.globalData.user;
      // 分享到地址
      const URL = Url.newInstance("/pages/index/index");
        URL
          .setPara('id', _this.data.ticket.id)
          .setPara('type', 'ticket')
      // 由于取消分享回调功能，所以只能这样处理
      _this.setData({ onPopupShow: false });
      //
      return {
        title: "我是：" + user.nickName,
        imageUrl: _this.data.b_service + _this.data.ticketImgUrl,
        // path: '/model_user/pages/card/card?id=' + _this.data.ticket.id
        path: URL.get()
      }
    },
    /**
     * 触底事件
     */
    onReachBottom: function () {
      const _this = this;
      let startPage = this.data.startPage + 1;
      ServiceTicket.page(startPage, function (data) {
        _this.data.tickets.push(...data.records);
        _this.setData({
          tickets: _this.data.tickets,
          startPage: startPage
        });
      });
    }
  }

})